package cm367;

import java.util.ArrayList;
import java.util.List;

import javax.faces.application.Application;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.event.AbortProcessingException;
import javax.faces.event.ActionEvent;
import javax.faces.event.ActionListener;

public class RequestValidator implements ActionListener{

	private List<User> nusers = new ArrayList<User>();

	@Override
	public void processAction(ActionEvent event) throws AbortProcessingException {
		FacesContext context = FacesContext.getCurrentInstance();
		Application app = context.getApplication();
		Request request = app.evaluateExpressionGet(context, "#{req}", Request.class);
		UserService userService = app.evaluateExpressionGet(context, "#{userService}", UserService.class);

		if (!request.isValid()){
			context.addMessage("f:w", new FacesMessage(
					FacesMessage.SEVERITY_ERROR,
					"Password and retype password must be same",
					null));
			throw new AbortProcessingException();
		} else {
			
			nusers = userService.getUsers();
			
			nusers.add(new User(request.getName(), 
								request.getEmail(), 
								"user",
								request.getPassword(),
								request.getTitle(),
								request.getTelNo()));
		}
		
	}

}
